import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router-dom';
import { 
  message, 
  Spin, 
  Layout,
} from 'antd';
import { 
  ClockCircleOutlined,
  QuestionCircleOutlined,
  CodepenOutlined,
  PlayCircleOutlined,
  FileTextOutlined,
  SendOutlined
} from '@ant-design/icons';
import { problemService } from '@/services/problemService';
import { submissionService } from '@/services/submissionService';
import { Problem } from '@/types/problem';
import { EditorSettings, defaultSettings } from '@/types/editor';
import { useAuthStore } from '@/store/useAuthStore';
import styles from './Submit.module.css';
import { extractErrorsFromDebugResult, isCompileError, ErrorInfo } from '@/utils/errorParser';
import CollapsibleCard, { CardState } from '@/components/CollapsibleCard';
import CollapsibleTabCard, { TabItem } from '@/components/CollapsibleTabCard';
import ProblemHeader from './components/ProblemHeader';
import ProblemDescription from './components/ProblemDescription';
import CodeEditor from './components/CodeEditor';
import Resizer from '@/components/Resizer';
import SubmissionList from './components/SubmissionList';
import TestResult from './components/TestResult';
import SubmissionResult from './components/SubmissionResult';
import CelebrationAnimation from './components/CelebrationAnimation';
const { Content } = Layout;

const DEFAULT_PROBLEM_WIDTH = 50; // 默认问题卡片宽度比例(%)
const MIN_PROBLEM_WIDTH = 20; // 最小问题宽度
const MAX_PROBLEM_WIDTH = 80; // 最大问题宽度

// 添加提交结果状态码映射
const SUBMISSION_STATUS = {
  COMPILE_ERROR: -2,        // 编译错误
  WRONG_ANSWER: -1,         // 答案错误
  ACCEPTED: 0,              // 通过
  CPU_TIME_LIMIT_EXCEEDED: 1, // CPU时间超限
  REAL_TIME_LIMIT_EXCEEDED: 2, // 实际时间超限
  MEMORY_LIMIT_EXCEEDED: 3, // 内存超限
  RUNTIME_ERROR: 4,         // 运行时错误
  SYSTEM_ERROR: 5,          // 系统错误
  PENDING: 6,               // 等待评测
  JUDGING: 7,               // 评测中
  PARTIALLY_ACCEPTED: 8     // 部分通过(OI模式)
};

// 提交结果状态码对应的文字描述
const STATUS_TEXT: Record<number, string> = {
  [-2]: '编译错误',
  [-1]: '答案错误',
  [0]: '通过',
  [1]: 'CPU时间超限',
  [2]: '实际时间超限',
  [3]: '内存超限',
  [4]: '运行时错误',
  [5]: '系统错误',
  [6]: '等待评测',
  [7]: '评测中',
  [8]: '部分通过'
};

// 提交结果状态码对应的颜色
const STATUS_COLOR: Record<number, string> = {
  [-2]: 'pink',     // 编译错误
  [-1]: 'error',    // 答案错误
  [0]: 'success',   // 通过
  [1]: 'orange',    // CPU时间超限
  [2]: 'orange',    // 实际时间超限
  [3]: 'purple',    // 内存超限
  [4]: 'warning',   // 运行时错误
  [5]: 'error',     // 系统错误
  [6]: 'default',   // 等待评测
  [7]: 'processing', // 评测中
  [8]: 'blue'       // 部分通过
};

const ProblemSubmit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { clearAuth, user, isAuthenticated } = useAuthStore();
  const [searchParams] = useSearchParams();
  const contestId = searchParams.get('contest_id');
  
  const [problem, setProblem] = useState<Problem | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [language, setLanguage] = useState('C++');
  const [code, setCode] = useState('');
  const [editorSettings, setEditorSettings] = useState<EditorSettings>(defaultSettings);
  const [submissionResult, setSubmissionResult] = useState<any>(null);
  const [testResult, setTestResult] = useState<any>(null);
  const [testInput, setTestInput] = useState<string>('');
  const [expectedOutput, setExpectedOutput] = useState<string>('');
  const [resultActiveTab, setResultActiveTab] = useState<string>('testResult');
  const [currentSubmissionId, setCurrentSubmissionId] = useState<string | null>(null);
  const [compileErrors, setCompileErrors] = useState<ErrorInfo[]>([]);
  const [pollTimer, setPollTimer] = useState<NodeJS.Timeout | null>(null);
  const [showCelebration, setShowCelebration] = useState(false);
  
  // 卡片状态
  const [problemCardState, setProblemCardState] = useState<CardState>('normal');
  const [editorCardState, setEditorCardState] = useState<CardState>('normal');
  const [resultCardState, setResultCardState] = useState<CardState>('normal');
  const [problemWidth, setProblemWidth] = useState<number>(DEFAULT_PROBLEM_WIDTH);
  
  const [activeTab, setActiveTab] = useState<string>('description');
  
  
  // 从localStorage获取保存的宽度设置
  useEffect(() => {
    const userId = user?.id?.toString() || 'anonymous';
    const savedWidth = localStorage.getItem(`problemWidth_${userId}`);
    if (savedWidth) {
      setProblemWidth(Number(savedWidth));
    }
  }, [user?.id]);

  
  // 获取题目信息
  useEffect(() => {
    const fetchProblem = async () => {
      if (!id) return;
      
      try {
        setLoading(true);
        const response = await problemService.getProblem(Number(id), contestId ? { contest_id: Number(contestId) } : undefined);
        
        // 检查响应数据结构
        if (response.data && typeof response.data === 'object') {
          // 如果response.data是ResponseData类型，则取其data属性
          if ('data' in response.data) {
            setProblem(response.data.data as Problem);
          } else {
            // 如果response.data直接就是Problem类型
            setProblem(response.data as Problem);
          }
        } else {
          throw new Error('Invalid response format');
        }
        
        // 默认设置为C++，不使用模板
        setLanguage('C++');
        setCode('');
      } catch (error) {
        message.error('获取题目失败');
      } finally {
        setLoading(false);
      }
    };
    
    fetchProblem();
  }, [id, contestId]);

  // 当题目ID变化时，重置结果相关状态
  useEffect(() => {
    // 重置提交结果相关状态
    setSubmissionResult(null);
    setTestResult(null);
    setResultActiveTab('testResult');
    setCurrentSubmissionId(null);
    setTestInput('');
    setExpectedOutput('');
    setSubmitting(false);
    
    // 重置题目标签页为默认状态
    setActiveTab('description');
    
    // 重置庆祝动画状态
    setShowCelebration(false);
    
    // 清除轮询定时器
    if (pollTimer) {
      clearInterval(pollTimer);
      setPollTimer(null);
    }
  }, [id]);
  
  // 处理区域大小调整
  const handleResize = (delta: number) => {
    console.log(`Submit: 接收到Resize事件，原始delta=${delta}`);
    
    // 将delta转换为百分比变化 (像素 -> 百分比)
    const deltaPercent = (delta / window.innerWidth) * 100;
    
    // 计算新的宽度，并限制在最小/最大范围内
    const newWidth = Math.max(
      MIN_PROBLEM_WIDTH,
      Math.min(MAX_PROBLEM_WIDTH, problemWidth + deltaPercent)
    );
    
    // 只有当宽度真正变化时才更新
    if (newWidth !== problemWidth) {
      console.log(`Submit: 调整宽度: delta=${delta}px, 百分比=${deltaPercent.toFixed(2)}%, 新宽度=${newWidth.toFixed(2)}%, 原宽度=${problemWidth.toFixed(2)}%`);
      setProblemWidth(newWidth);
      
      // 保存到localStorage
      const userId = user?.id?.toString() || 'anonymous';
      localStorage.setItem(`problemWidth_${userId}`, newWidth.toString());
    }
  };
  
  // 提交代码
  const handleSubmit = async () => {
    if (!id || !code.trim()) return;
    
    try {
      setSubmitting(true);
      // 优先使用 problem.contest_id，其次使用 URL 参数中的 contestId
      const finalContestId = problem?.contest_id || (contestId ? Number(contestId) : null);
      
      const response = await submissionService.submit({
        problem: Number(id),
        language,
        code,
        contest_id: finalContestId
      });
      
      // 检查响应数据结构，获取提交ID
      let submissionId = null;
      let submissionData = null;
      
      if (response.data && typeof response.data === 'object') {
        // 如果response.data是ResponseData类型，则取其data属性
        if ('data' in response.data && response.data.data && typeof response.data.data === 'object') {
          submissionData = response.data.data;
          if ('id' in response.data.data) {
            submissionId = response.data.data.id;
          }
        } 
        // 如果response.data直接就是提交结果类型
        else if ('id' in response.data) {
          submissionData = response.data;
          submissionId = response.data.id;
        }
      }
      
      if (submissionData) {
        setSubmissionResult(submissionData);
        message.success('提交成功');
        
        // 显示提交结果
        setResultActiveTab('submissionResult');
        setResultCardState('normal');
        
        // 如果获取到了提交ID，并且状态是等待评测或评测中，开始轮询
        if (submissionId && (
            (submissionData as any).result === SUBMISSION_STATUS.PENDING || 
            (submissionData as any).result === SUBMISSION_STATUS.JUDGING
        )) {
          setCurrentSubmissionId(String(submissionId));
          startPollingSubmission(String(submissionId));
        }
      } else {
        message.warning('提交成功，但无法获取提交ID');
      }
    } catch (error) {
      console.error('提交失败:', error);
      message.error('提交失败');
    } finally {
      setSubmitting(false);
    }
  };
  
  // 运行测试
  const handleTest = async () => {
    if (!id || !code.trim()) return;
    
    try {
      setSubmitting(true);
      // 清除之前的错误信息
      setCompileErrors([]);
      // 切换到测试结果标签
      setResultActiveTab('testResult');
      setResultCardState('normal');
      
      // 构建测试用例
      const test_case = [
        {
          input: testInput || '',
          output: expectedOutput || ''
        }
      ];
      
      // 优先使用 problem.contest_id，其次使用 URL 参数中的 contestId
      const finalContestId = problem?.contest_id || (contestId ? Number(contestId) : null);
      
      // 提交调试请求
      const response = await submissionService.debug({
        problem_id: Number(id),
        language,
        code,
        test_case,
        contest_id: finalContestId
      });
      
      // 获取调试ID
      let debugId = '';
      if (response.data && typeof response.data === 'object') {
        if ('data' in response.data && response.data.data && typeof response.data.data === 'object') {
          debugId = response.data.data.debug_id;
        }
      }
      
      if (debugId) {
        // 开始轮询调试结果
        startPollingDebugResult(debugId);
      } else {
        message.warning('调试请求成功，但无法获取调试ID');
        setSubmitting(false);
      }
    } catch (error) {
      console.error('调试失败:', error);
      message.error('调试失败');
      setSubmitting(false);
    }
  };
  
  // 处理卡片状态变化
  const handleProblemCardChange = (state: CardState) => {
    const prevState = problemCardState;
    setProblemCardState(state);
    
    // 从折叠状态恢复到正常状态时，恢复宽度
    if ((prevState === 'collapsedLeft' || prevState === 'collapsedRight') && state === 'normal') {
      // 延迟设置宽度，确保DOM已更新
      setTimeout(() => {
        setProblemWidth(DEFAULT_PROBLEM_WIDTH);
      }, 0);
    }
  };
  
  const handleEditorCardChange = (state: CardState) => {
    setEditorCardState(state);
    
    // 当编辑器折叠时，自动调整结果卡片的状态
    if (state === 'collapsedUp' && resultCardState === 'collapsedDown') {
      setResultCardState('normal'); // 如果结果卡片也是折叠的，则展开它
    }
  };
  
  const handleResultCardChange = (state: CardState) => {
    setResultCardState(state);
    
    // 当结果卡片折叠时，自动调整编辑器卡片的状态
    if (state === 'collapsedDown' && editorCardState === 'collapsedUp') {
      setEditorCardState('normal'); // 如果编辑器也是折叠的，则展开它
    }
  };
  
  const handleLanguageChange = (value: string) => {
    setLanguage(value);
  };
  
  // 渲染题目描述内容
  const renderProblemContent = () => {
    return (
      <div className={styles.problemContent}>
        <ProblemDescription problem={problem} />
      </div>
    );
  };
  
  // 渲染代码编辑器内容
  const renderEditorContent = () => {
    return (
      <CodeEditor
        value={code}
        language={language}
        editorSettings={editorSettings}
        onChange={setCode}
        onLanguageChange={handleLanguageChange}
        problemId={id}
        errors={compileErrors}
      />
    );
  };
{/* <CodeEditor
  value={problemAnswer.code}
  language={problemAnswer.language}
  onChange={onCodeChange}
  onLanguageChange={onLanguageChange}
  editorSettings={editorSettings}
  problemId={problem._id}
/> */}
  
  // 渲染提交记录内容
  const renderSubmissionsContent = () => {
    if (!id) {
      return (
        <div className={styles.emptyResult}>
          <QuestionCircleOutlined className={styles.emptyIcon} />
          <p>题目ID未提供，无法加载提交记录</p>
        </div>
      );
    }
    
    return (
      <div className={styles.submissionsContent}>
        <SubmissionList problemId={Number(id)} />
      </div>
    );
  };
  
  // 渲染结果标签页内容
  const resultTabs: TabItem[] = [
    {
      key: 'testResult',
      tab: <><PlayCircleOutlined /> 运行结果</>,
      content: (
        <TestResult
          testInput={testInput}
          testResult={testResult}
          submitting={submitting}
          resultActiveTab={resultActiveTab}
          onTestInputChange={setTestInput}
          onTest={handleTest}
          expectedOutput={expectedOutput}
          onExpectedOutputChange={setExpectedOutput}
        />
      )
    },
    {
      key: 'submissionResult',
      tab: <><FileTextOutlined /> 提交结果</>,
      content: (
        <SubmissionResult
          submissionResult={submissionResult}
          submitting={submitting}
          resultActiveTab={resultActiveTab}
        />
      )
    }
  ];
  
  // 处理结果标签页切换
  const handleResultTabChange = (key: string) => {
    setResultActiveTab(key);
  };
  
  const handleTabChange = (key: string) => {
    setActiveTab(key);
  };
  
  const problemTabs: TabItem[] = [
    {
      key: 'description',
      tab: <><QuestionCircleOutlined /> 题目描述</>,
      content: renderProblemContent()
    },
    {
      key: 'submissions',
      tab: <><ClockCircleOutlined /> 提交记录</>,
      content: renderSubmissionsContent()
    }
  ];
  
  // 获取提交详情
  const fetchSubmissionDetail = async (submissionId: string) => {
    try {
      const response = await submissionService.getSubmissionDetail(submissionId);
      // 处理响应数据
      let submissionDetail = null;
      if (response.data && typeof response.data === 'object') {
        // 如果response.data是ResponseData类型，则取其data属性
        if ('data' in response.data) {
          submissionDetail = response.data.data;
        } else {
          // 如果response.data直接就是提交结果类型
          submissionDetail = response.data;
        }
      }
      
      if (submissionDetail) {
        setSubmissionResult(submissionDetail);
        
        // 检查提交状态，如果仍在等待或评测中，继续轮询
        if (submissionDetail.result === SUBMISSION_STATUS.PENDING || 
            submissionDetail.result === SUBMISSION_STATUS.JUDGING) {
          // 继续轮询
          return false;
        } else {
          // 评测完成，检查是否通过
          if (submissionDetail.result === SUBMISSION_STATUS.ACCEPTED) {
            // 触发庆祝动画
            setShowCelebration(true);
          }
          // 停止轮询
          return true;
        }
      }
      return true; // 如果无法获取数据，停止轮询
    } catch (error) {
      console.error('获取提交详情失败:', error);
      message.error('获取提交详情失败');
      return true; // 出错时停止轮询
    }
  };

  // 开始轮询提交结果
  const startPollingSubmission = (submissionId: string) => {
    // 清除可能存在的旧定时器
    if (pollTimer) {
      clearInterval(pollTimer);
    }
    
    // 立即获取一次提交结果
    fetchSubmissionDetail(submissionId).then(shouldStop => {
      if (!shouldStop) {
        // 开始定时轮询，每2秒获取一次
        const timer = setInterval(async () => {
          const shouldStop = await fetchSubmissionDetail(submissionId);
          if (shouldStop) {
            clearInterval(timer);
            setPollTimer(null);
          }
        }, 2000);
        
        setPollTimer(timer);
      }
    });
  };

  // 当currentSubmissionId变化时，自动启动轮询
  useEffect(() => {
    if (currentSubmissionId) {
      startPollingSubmission(currentSubmissionId);
    }
  }, [currentSubmissionId]);

  // 组件卸载时清除定时器
  useEffect(() => {
    return () => {
      if (pollTimer) {
        clearInterval(pollTimer);
      }
    };
  }, [pollTimer]);
  
  // 获取调试结果
  const fetchDebugResult = async (debugId: string) => {
    try {
      const response = await submissionService.getDebugResult(debugId);
      
      // 处理响应数据
      let debugResult = null;
      if (response.data && typeof response.data === 'object') {
        if ('data' in response.data) {
          debugResult = response.data.data;
        } else {
          debugResult = response.data;
        }

      }
      
      if (debugResult) {
        // 解析编译错误信息
        if (isCompileError(debugResult.result)) {
          const parsedErrors = extractErrorsFromDebugResult(debugResult);
          setCompileErrors(parsedErrors.errors);
        } else {
          setCompileErrors([]);
        }
        
        // 更新测试结果
        setTestResult({
          status: debugResult.result === SUBMISSION_STATUS.ACCEPTED ? 'Accepted' : 'Failed',
          runtime: `${debugResult.statistic_info?.time_cost || 0} ms`,
          memory: `${debugResult.statistic_info?.memory_cost || 0} KB`,
          testCases: debugResult.info?.data?.map((item: any) => ({
            input: testInput || '',
            output: item.output || '',
            expected: '',
            result: item.result === SUBMISSION_STATUS.ACCEPTED ? 'Pass' : 'Fail'
          })) || [],
          errorInfo: debugResult.statistic_info?.err_info || ''
        });
        
        // 检查调试状态，如果仍在等待或评测中，继续轮询
        if (debugResult.result === SUBMISSION_STATUS.PENDING || 
            debugResult.result === SUBMISSION_STATUS.JUDGING) {
          // 继续轮询
          return false;
        } else {
          // 评测完成，停止轮询
          setSubmitting(false);
          return true;
        }
      }
      
      setSubmitting(false);
      return true; // 如果无法获取数据，停止轮询
    } catch (error) {
      console.error('获取调试结果失败:', error);
      message.error('获取调试结果失败');
      setSubmitting(false);
      return true; // 出错时停止轮询
    }
  };

  // 开始轮询调试结果
  const startPollingDebugResult = (debugId: string) => {
    // 清除可能存在的旧定时器
    if (pollTimer) {
      clearInterval(pollTimer);
    }
    
    // 立即获取一次调试结果
    fetchDebugResult(debugId).then(shouldStop => {
      if (!shouldStop) {
        // 开始定时轮询，每2秒获取一次
        const timer = setInterval(async () => {
          const shouldStop = await fetchDebugResult(debugId);
          if (shouldStop) {
            clearInterval(timer);
            setPollTimer(null);
          }
        }, 2000);
        
        setPollTimer(timer);
      }
    });
  };
  
  const handleLogout = () => {
    clearAuth();
    navigate('/login');
  };

  // 处理庆祝动画结束
  const handleCelebrationEnd = () => {
    setShowCelebration(false);
  };
  
  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <Spin>
          <div className={styles.loadingPlaceholder} style={{ minHeight: '200px' }} />
        </Spin>
      </div>
    );
  }
  
  // 根据problemCardState确定CSS类名
  const getProblemCardWrapperClassName = () => {
    const classNames = [styles.problemCardWrapper];
    if (problemCardState === 'collapsedLeft' || problemCardState === 'collapsedRight') {
      classNames.push(styles.collapsed);
    }
    return classNames.join(' ');
  };
  
  // 根据editorCardState确定CSS类名
  const getEditorCardWrapperClassName = () => {
    const classNames = [styles.editorCardWrapper];
    if (editorCardState === 'collapsedUp') {
      classNames.push(styles.collapsedUp);
    } else if (editorCardState === 'collapsedDown') {
      classNames.push(styles.collapsedDown);
    }
    return classNames.join(' ');
  };
  
  // 根据resultCardState确定CSS类名
  const getResultCardWrapperClassName = () => {
    const classNames = [styles.resultCardWrapper];
    if (resultCardState === 'collapsedDown') {
      classNames.push(styles.collapsedDown);
    } else if (resultCardState === 'collapsedUp') {
      classNames.push(styles.collapsedUp);
    }
    return classNames.join(' ');
  };
  
  return (
    <Layout className={styles.layout}>
      <ProblemHeader 
        id={id}
        problem={problem || undefined}
        isAuthenticated={isAuthenticated}
        user={user}
        submitting={submitting}
        onTest={handleTest}
        onSubmit={handleSubmit}
        onLogout={handleLogout}
      />
      
      <Content className={styles.content}>
        <div className={styles.cardsContainer}>
          {/* 题目描述卡片 */}
          <div 
            className={getProblemCardWrapperClassName()}
            style={{
              width: problemCardState === 'normal' ? `${problemWidth}%` : undefined,
              flexShrink: 0,
              flexGrow: 0
            }}
          >
            <CollapsibleTabCard
              tabs={problemTabs}
              activeKey={activeTab}
              onTabChange={handleTabChange}
              className={styles.problemCard}
              defaultState={problemCardState}
              collapseDirections={['left']}
              onChange={handleProblemCardChange}
              wrapperClassName={styles.cardWrapper}
            />
          </div>
          
          {/* 调整区域比例的分隔符 */}
          {problemCardState === 'normal' && (
            <Resizer 
              direction="vertical"
              onResize={handleResize} 
              className={styles.problemResizer}
            />
          )}
          
          <div 
            className={styles.rightCards}
            style={{
              width: problemCardState === 'normal' ? `calc(100% - ${problemWidth}% - 12px)` : undefined,
              flexShrink: 0,
              flexGrow: 1
            }}
          >
            {/* 代码编辑器卡片 */}
            <div className={getEditorCardWrapperClassName()}>
              <CollapsibleCard
                title={<><CodepenOutlined /> 代码</>}
                className={styles.editorCard}
                defaultState={editorCardState}
                collapseDirections={['up']}
                onChange={handleEditorCardChange}
                wrapperClassName={styles.cardWrapper}
              >
                {renderEditorContent()}
              </CollapsibleCard>
            </div>
            
            {/* 执行结果卡片 - 改为标签卡片 */}
            <div className={getResultCardWrapperClassName()}>
              <CollapsibleTabCard
                tabs={resultTabs}
                activeKey={resultActiveTab}
                onTabChange={handleResultTabChange}
                className={styles.resultCard}
                defaultState={resultCardState}
                collapseDirections={['down']}
                onChange={handleResultCardChange}
                wrapperClassName={styles.cardWrapper}
              />
            </div>
          </div>
        </div>
      </Content>
      
      {/* 庆祝动画 */}
      <CelebrationAnimation 
        visible={showCelebration}
        onAnimationEnd={handleCelebrationEnd}
      />
    </Layout>
  );
};

export default ProblemSubmit;
